// socket.io specific code

var socket = io.connect("/chat");//, resource:"chat");

var socket_game = io.connect("/game");//, resource:"chat");

socket.on('connect', function () {
    $('#chat').addClass('connected');
    socket.emit('join', window.room); 
});

socket_game.on('connect', function () {
    //$('#chat').addClass('connected');
    console.log("socket_game conectado");
    socket_game.emit('join', window.room);
});


socket.on('announcement', function (msg) {
    $('#lines').append($('<p>').append($('<em>').text(msg)));
});


socket_game.on('players', function (players_names, players_points) {
    console.log('Actualizando players..');
    $('#players').empty();

    // Selection Sort n^2: Provisional
    for (var i=0; i<players_points.length-1; i++) {
        var mini = i;
        for(var j = i+1; j<players_points.length; j++){
            if(players_points[mini] < players_points[j]) mini = j;
        }
        var tmp = players_points[mini];
        players_points[mini] = players_points[i];
        players_points[i] = tmp;

        var tmp2 = players_names[mini];
        players_names[mini] = players_names[i];
        players_names[i] = tmp2;
    }

    for (var i in players_names) {
	  $('#players').append($('<div>').text(players_names[i] + " - " + players_points[i]));
    }

});


socket_game.on('resources', function(num_resources){
    console.log('Actualizando recursos...');
    $('#resources').html(parseInt(num_resources));
});


socket_game.on('ants', function(ants_types, ants_nums){
    console.log('Actualizando ejército...');
    $('#ants').empty();

    for (var i in ants_types) {
	  $('#ants').append($('<div>').text(ants_types[i] + " - " + ants_nums[i]));
    }

});


socket.on('nicknames', function (nicknames) {
    $('#nicknames').empty().append($('<span>Online: </span>'));
    // ordenar nicknames por 'points'
    for (var i in nicknames) {
	  $('#nicknames').append($('<b>').text(nicknames[i]));
    }

});

socket.on('msg_to_room', message);

socket.on('reconnect', function () {
    $('#lines').remove();
    message('System', 'Reconnected to the server');
});

socket.on('reconnecting', function () {
    message('System', 'Attempting to re-connect to the server');
});

socket.on('error', function (e) {
    message('System', e ? e : 'A unknown error occurred');
});

function message (from, msg) {
    $('#lines').append($('<p>').append($('<b>').text(from), msg));
}


function new_ant(type_ant){
    socket_game.emit('new_ant', type_ant, function(set){
        if(set){
            console.log("Hormiga creada con éxito!");
            return false;
        }else{
            alert("Problemas  al crear la hormiga...");
        }
    });
}

// DOM manipulation
$(function () {
    $('#set-nickname').submit(function (ev) {

        socket.emit('nickname', $('#nick').val(), function (set) {
            if (set) {
                clear();
                return $('#chat').addClass('nickname-set');
            }
            $('#nickname-err').css('visibility', 'visible');
        });

        // GAME
        socket_game.emit('nickname', $('#nick').val(), function (set){
            if(set){
                //Cosas que hacer tras la conexión ...
                console.log("probando"  + set);
            } else {
                // otros errores...
                alert("Problemas, no hemos podido conectar con el socket game.");
            }
        });
        
        return false;
    });

    $('#send-message').submit(function () {
	    message('me', $('#message').val());
	    socket.emit('user message', $('#message').val());
	    clear();
	    $('#lines').get(0).scrollTop = 10000000;
	    return false;
    });



    function clear () {
        $('#message').val('').focus();
    };
});

